package com.szyjjk.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.szyjjk.entity.PageBo;
import com.szyjjk.entity.ResponseBo;
import com.szyjjk.entity.User;
import com.szyjjk.entity.UserBo;
import com.szyjjk.mapper.UserMapper;

@Service
@Transactional(readOnly = true)
public class UserService {

	@Autowired
	private UserMapper userMapper;

	public List<User> queryList() {

		try {
			return userMapper.queryList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 查询用户
	 * @param param
	 * @return
	 */
	public PageBo<UserBo> queryListByPage(Map<String, Object> param) {
		PageBo<UserBo> pb = new PageBo<UserBo>();
		pb.setPageNo(Integer.parseInt(param.get("pageNo")+""));
		pb.setPageSize(Integer.parseInt(param.get("pageSize")+""));
		try {
			// 总数量
			int counts = userMapper.queryListCounts(param);
			pb.setCounts(counts);
			if (counts == 0) {
				return pb;
			}
			List<UserBo> listUser = userMapper.queryListByPage(param);
			pb.setList(listUser);
		} catch (Exception e) {
			e.printStackTrace();
			pb.setCode(0);
			pb.setMessage("查询失败");
		}
		return pb;
	}


	/**
	 * @Author yangyue
	 * @Description //TODO 登陆查询
	 * @Date 16:44 2020/2/28
	 * @Param [userName, passWord]
	 * @return java.util.List<com.szyjjk.entity.UserBo>
	 **/
	public List<UserBo> loginQuery(String userName,String passWord) {
		Map<String, String> param =new HashedMap();
		param.put("userName",userName);
		param.put("passWord",passWord);
		List<UserBo> listUser = userMapper.querylogin(param);
		return listUser;
	}


	/**
	 * 新增、修改用户
	 * @param userBo
	 * @return
	 */
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public ResponseBo addUser(UserBo userBo) {
		ResponseBo rb = new ResponseBo();
		try {
			if(userBo.getId()==null) {
				//TODO  新增 数据库有唯一username  代码没校验
				userMapper.addUser(userBo);
			}else {
				//根据id更新
				userMapper.updateUser(userBo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			rb.setCode(0);
			rb.setMessage("保存失败");
		}
		return rb;
	}
	/**
	 * 删除用户
	 * @param userBo
	 * @return
	 */
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public ResponseBo delUser(UserBo userBo) {
		ResponseBo rb = new ResponseBo();
		try {
			//根据id 删除
			userMapper.delUser(userBo.getId());
		} catch (Exception e) {
			e.printStackTrace();
			rb.setCode(0);
			rb.setMessage("保存失败");
		}
		return rb;
	}
	public UserBo queryLogin(UserBo userBo) {
		try {
			return userMapper.queryLogin(userBo);
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		return null;
	}

}
